import { Button, Modal,Form,Input } from 'antd';
import React, { useState ,useRef ,useEffect } from 'react';
import {useDispatch,useSelector} from "react-redux"
import * as action from "../action"
// 该组件是一个公共组件，通过父组件给其传递不同的参数来实现编辑和新增的功能
const App = ({addShow,closeaddfn,editIndex,editItem,isadd}) => {
  let dispatch = useDispatch()
  let store = useSelector(state=>({...state.tablereducer}))
  let myref = useRef(null)
  const [isModalOpen, setIsModalOpen] = useState(false);
  const showModal = () => {
    setIsModalOpen(true);
  };
  const handleCancel = () => {
    closeaddfn(false)
  };
   useEffect(()=>{
    if (isadd === "新增") {
        myref.current &&  myref.current.resetFields()
    } else {
        myref.current &&  myref.current.setFieldsValue(editItem)

    } // x相当于componentDidupdat // watch

   },[isadd,editItem])
  const onFinish = (values) => { // 将values追加到仓库就可以啦
     // 判断是走新增逻辑还是编辑逻辑
    console.log('Success:', values);
    values.key = Math.random()
    if (isadd === "新增") {
        dispatch(action.addfn(values))
    } else {
        // 1.在组件中dispactch action 里的方法
        // 2. 去acion中写这个方法
        // 3. 去写对应的reducer
        dispatch(action.editFn(Object.assign({},values,{editIndex})))
    }
   
   
    console.log(myref.current,"ref");
    closeaddfn(false)
  };
  const onFinishFailed = (errorInfo) => {
    console.log('Failed:', errorInfo);
  };
  return (
    <>
     
      <Modal title={isadd} open={addShow}  onCancel={handleCancel} footer={null}>
      <Form
      name="basic"
      labelCol={{
        span: 8,
      }}
      ref={myref}
      wrapperCol={{
        span: 16,
      }}
      initialValues={{
        remember: true,
      }}
      onFinish={onFinish}
      onFinishFailed={onFinishFailed}
      autoComplete="off"
    >
      <Form.Item
        label="姓名"
        name="name"
        rules={[
          {
            required: true,
            message: 'Please input your username!',
          },
        ]}
      >
        <Input />
      </Form.Item>

      <Form.Item
        label="年龄"
        name="age"
        rules={[
          {
            required: true,
            message: 'Please input your password!',
          },
        ]}
      >
        <Input />
      </Form.Item>

      <Form.Item
        label="住址"
        name="address"
        rules={[
          {
            required: true,
            message: 'Please input your password!',
          },
        ]}
      >
        <Input />
      </Form.Item>

      <Form.Item
        wrapperCol={{
          offset: 8,
          span: 16,
        }}
      >
        <Button type="primary" htmlType="submit">
          Submit
        </Button>
      </Form.Item>
    </Form>
      </Modal>
    </>
  );
};
export default App;